// 用户相关仓库
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type  { LoginParams, UserState  } from '@/types/user'
import { loginAPI ,getUserInfoAPI, loginOutAPI } from '@/api/user'
import { ElNotification } from 'element-plus'
import { useDate } from '@/composables/useDate'
import { constantRoutes, asyncRoutes} from '@/router/modules/index.ts'
import { filterRoute } from '@/composables/useFilterRoute'




const useUserStore: any = defineStore('user',() =>  {

    // 用户信息
    const  userInfo = ref<UserState>({})

    // 系统路由信息
    const routerList: any= ref(constantRoutes)
    const newRoute = ref([]);

    // token
    const token = ref<string | undefined>('')

    // 用户登录
    const Login = async (data: LoginParams) => {
        const res = await loginAPI(data)

        // 判断是否登录成功
        if(res.code === 200) {
            // 获取当前时间段
            const { currentTime } = useDate()
            // 提示用户
            ElNotification({
                title: `Hi,${currentTime?.title}好！`,
                message: '欢迎回来！',
                type: 'success',
            })
            
            // 存入本地
            token.value = res.data
        }

        // 数据返回
        return res
    }

    // 获取用户信息
    const getUserInfo = async () => {
        const res  = await getUserInfoAPI()
        userInfo.value = res.data
        const arr = filterRoute(asyncRoutes, res.data.routes)
        if(JSON.stringify(arr) !== JSON.stringify(newRoute.value)) {
            newRoute.value = arr
            routerList.value = [...constantRoutes, ...arr]
        }

    }

    // 退出登录
    const logout = async () => {
        const res = await loginOutAPI()
        // console.log(res);
        if(res.code === 200) {
            // 清除用户数据
            token.value = ''
            userInfo.value = {}
        }
        
        
    }
    // 导出
    return {
        userInfo,
        token,
        Login,
        routerList,
        getUserInfo,
        logout
    }
},{
    // 持久化
    persist: true,
  })

// 默认导出
export default useUserStore